package com.picket.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import com.google.appengine.api.users.User;
import com.picket.domain.AppRole;
import com.picket.domain.GaeUser;
import com.picket.service.IGaeUserService;

public class GaeUserAuthProvider implements AuthenticationProvider {
    private IGaeUserService gaeUserService;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        User googleUser = (User) authentication.getPrincipal();

        GaeUser user = gaeUserService.findUser(googleUser.getUserId());

        if (user == null) {
            // User not in registry. Needs to register
            user = new GaeUser(googleUser.getUserId(),  googleUser.getEmail(),googleUser.getNickname());
            user.setEnabled(true);
            user.addAuthority(AppRole.NEW_USER);
        }

        if (!user.isEnabled()) {
            throw new DisabledException("Account is disabled");
        }

        return new GaeUserAuth(user, authentication.getDetails());
    }

    public final boolean supports(Class<?> authentication) {
        return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setGaeUserService(IGaeUserService gaeUserService) {
        this.gaeUserService = gaeUserService;
    }
}
